#include<iostream>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<cstdlib>
#include<string>
using namespace std;
int main()
{
    int fd[2] = {0};
    int n = pipe(fd);
    if(n != 0) return 1;
    string flag = "helloworld";
    // cout << "hello world" << endl;
    pid_t id = fork();
    if(id<0) return 1;
    else if(id == 0)
    {
        //3，关闭不需要的通道
        //子关闭写端
        close(fd[0]);
        int cut = 0;
        while(true)
        {
             flag += to_string(getpid());
             flag += ",";
             flag += to_string(cut);

             ::write(fd[1],flag.c_str(),flag.size());//通过管道写给另一个进程

             cut++;
             sleep(1);
        }
        
        exit(0);
    }
    else
    {
         //关系读端
         close(fd[1]);
         char buffer[1024];
         while(true)
         {
             ssize_t n = ::read(fd[0],buffer,1024);
             if(n > 0)
             {
                 buffer[n] = 0;
                 cout << "child -> father" << buffer << endl;
             }
         }
         pid_t rid = waitpid(id,nullptr,0);
         cout << ""<< rid << endl;
    }
    return 0;
}